package com.wfm.queues;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayedTask> queue = new DelayQueue<>();

        // 添加带有延迟的任务
        queue.put(new DelayedTask("任务A", 3000));
        queue.put(new DelayedTask("任务B", 1000));
        queue.put(new DelayedTask("任务C", 5000));

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                while (!queue.isEmpty()) {
                    DelayedTask task = queue.take();
                    System.out.println("执行任务: " + task.name);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        consumer.start();
        consumer.join();
    }

    static class DelayedTask implements Delayed {
        String name;
        long startTime;

        public DelayedTask(String name, long delayInMillis) {
            this.name = name;
            this.startTime = System.currentTimeMillis() + delayInMillis;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long diff = startTime - System.currentTimeMillis();
            return unit.convert(diff, TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.startTime, ((DelayedTask) o).startTime);
        }
    }
}